package com.aop.demo.cglib.proxy;

import com.aop.demo.aspect.MyAspect;
import com.aop.demo.service.impl.SubjectServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author zlj
 */
public class CGlibProxy {

    public static SubjectServiceImpl createSubject() {
        final SubjectServiceImpl subject = new SubjectServiceImpl();
        final MyAspect myAspect = new MyAspect();

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(subject.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                myAspect.before();

                Object result = method.invoke(subject, objects);

                //等价于 执行代理类（子类）的父类方法 （父类就是目标类）
               // Object result = methodProxy.invokeSuper(proxy, objects);

                myAspect.after();
                return result;
            }
        });

        return (SubjectServiceImpl) enhancer.create();
    }
}
